#! /usr/bin/env python

from django.core.management import setup_environ
from django.core.handlers.wsgi import WSGIHandler
from DWPortAuth.wsgiserver import CherryPyWSGIServer
from DWPortAuth import Daemon
from optparse import OptionParser
import sys


class DjangoDaemon(Daemon):
    """docstring for DjangoDaemon"""
    
    def __init__(self, *args, **kwargs):
        # try to get the settings string from the kwargs if there isn't one 
        # assume it is just settings in the same path
        self.settings = kwargs.pop('settings', 'settings') 
        super(DjangoDaemon, self).__init__(*args, **kwargs)
        
    
    def start(self):
        settings = __import__(self.settings, {}, {}, [''])
        setup_environ(settings)
        super(DjangoDaemon, self).start()

    def run(self):
        pass


class WSGIDaemon(DjangoDaemon):
    def __init__(self, *args, **kwargs):
        self.port = int(kwargs.pop('port', 8000))
        self.address = kwargs.pop('address', '127.0.0.1')
        if ':' in self.address:
            self.address, self.port = self.address.split(':')
        kwargs['pidfile'] = '/tmp/wsgiserver%s%s.pid' % (self.address.replace('.',''), self.port)
        super(WSGIDaemon, self).__init__(*args, **kwargs)


    def load(self):
        app = WSGIHandler()
        self.server = CherryPyWSGIServer(
            (self.address, int(self.port)),
            app
        )

    def run(self):
        self.server.start()

def main():
    parser = OptionParser()
    parser.add_option('-s','--settings',metavar='MODULE', default='setting',
        help='The Django settings module (in the python path) to load')
    parser.add_option('-a','--address',metavar="ADDRESS",
        help="The address the server should run on", default='127.0.0.1')
    parser.add_option('-p','--port', metavar='PORT', default='8000',
        help='Port to run the WSGI server on')
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("Incorrect number of arguments")
    [action] = args
    server = WSGIDaemon(**options.__dict__)
    if action == 'start':
        server.start()
    elif action == 'stop':
        server.stop()
    elif action == 'restart':
        server.restart()
    else:
        raise Usage('%s must have start|stop|restart command' % argv[0])

if __name__ == "__main__":
    sys.exit(main())

